import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class CinemaSystem {
    private static UserService userService = new UserService();
    private static MovieService movieService = new MovieService();
    private static List<Hall> halls = new ArrayList<>();
    private static ShowService showService;
    private static TicketService ticketService = new TicketService();
    private static Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        initHalls();
        showService = new ShowService(halls, movieService);
        start();
        saveAllData();
        scanner.close();
    }

    private static void initHalls() {
        halls.add(new Hall("黄金厅", 8, 10));
        halls.add(new Hall("白银厅", 10, 12));
        halls.add(new Hall("翡翠厅", 7, 8));
    }

    private static void start() {
        System.out.println("===== 万东电影院管理系统 v1.1 =====");
        while (true) {
            System.out.println("1. 登录  2. 退出");
            System.out.print("请选择: ");
            int choice = scanner.nextInt();
            scanner.nextLine();  // 消费换行符

            if (choice == 1) {
                login();
            } else if (choice == 2) {
                System.out.println("系统已退出，感谢使用！");
                break;
            } else {
                System.out.println("无效选择，请重试");
            }
        }
    }

    // 用户登录逻辑
    private static void login() {
        System.out.print("用户名: ");
        String username = scanner.nextLine();
        System.out.print("密码: ");
        String password = scanner.nextLine();

        User user = userService.login(username, password);
        if (user != null) {
            UserContext.setCurrentUser(user);
            System.out.println("登录成功！欢迎回来，" + username);
            handleUserOperation(user);
            UserContext.clear();
        } else {
            System.out.println("用户名或密码错误");
        }
    }

    // 处理用户操作（根据角色显示不同菜单）
    private static void handleUserOperation(User user) {
        boolean running = true;
        while (running) {
            user.showMenu();
            int choice = scanner.nextInt();
            scanner.nextLine();  // 消费换行符

            switch (user.getUserType()) {
                case ADMIN:
                    running = handleAdminOperation(choice);
                    break;
                case MANAGER:
                    running = handleManagerOperation(choice);
                    break;
                case RECEPTIONIST:
                    running = handleReceptionistOperation(choice);
                    break;
            }
        }
    }

    // 管理员操作处理
    private static boolean handleAdminOperation(int choice) {
        switch (choice) {
            case 1:
                addNewUser();
                break;
            case 2:
                listAllUsers();
                break;
            case 3:
                changePassword();
                break;
            case 4:
                System.out.println("退出登录");
                return false;
            default:
                System.out.println("无效选择");
        }
        return true;
    }

    // 经理操作处理
    private static boolean handleManagerOperation(int choice) {
        switch (choice) {
            case 1:
                addNewMovie();
                break;
            case 2:
                queryMovies();
                break;
            case 3:
                listAllShows();
                break;
            case 4:
                changePassword();
                break;
            case 5:
                System.out.println("退出登录");
                return false;
            default:
                System.out.println("无效选择");
        }
        return true;
    }

    // 前台操作处理
    private static boolean handleReceptionistOperation(int choice) {
        switch (choice) {
            case 1:
                sellTicket();
                break;
            case 2:
                refundTicket();
                break;
            case 3:
                listAllShows();
                break;
            case 4:
                changePassword();
                break;
            case 5:
                System.out.println("退出登录");
                return false;
            default:
                System.out.println("无效选择");
        }
        return true;
    }

    // 添加新用户（管理员功能）
    private static void addNewUser() {
        System.out.println("\n===== 添加新用户 =====");
        System.out.print("用户ID: ");
        String userId = scanner.nextLine();
        System.out.print("用户名: ");
        String username = scanner.nextLine();
        System.out.print("密码: ");
        String password = scanner.nextLine();
        System.out.print("手机号: ");
        String phone = scanner.nextLine();
        
        System.out.println("用户类型: 1.管理员 2.经理 3.前台");
        System.out.print("选择类型: ");
        int type = scanner.nextInt();
        scanner.nextLine();

        User user = null;
        switch (type) {
            case 1:
                user = new Admin(userId, username, password, phone);
                break;
            case 2:
                user = new Manager(userId, username, password, phone);
                break;
            case 3:
                user = new Receptionist(userId, username, password, phone);
                break;
            default:
                System.out.println("无效用户类型");
                return;
        }

        if (user != null && userService.addUser(user)) {
            System.out.println("用户添加成功");
        } else {
            System.out.println("用户添加失败（ID或用户名已存在）");
        }
    }

    // 列出所有用户（管理员功能）
    private static void listAllUsers() {
        System.out.println("\n===== 所有用户 =====");
        for (User user : userService.getAllUsers()) {
            System.out.printf("ID: %s, 用户名: %s, 类型: %s, 注册时间: %s%n",
                    user.getUserId(), user.getUsername(), user.getUserType(),
                    user.getRegisterTime().toString().substring(0, 19));
        }
    }

    // 添加新影片（经理功能）
    private static void addNewMovie() {
        System.out.println("\n===== 添加新影片 =====");
        System.out.print("影片ID: ");
        String movieId = scanner.nextLine();
        System.out.print("影片名称: ");
        String name = scanner.nextLine();
        System.out.print("导演: ");
        String director = scanner.nextLine();
        System.out.print("主演: ");
        String actor = scanner.nextLine();
        System.out.print("简介: ");
        String intro = scanner.nextLine();
        System.out.print("时长(分钟): ");
        int duration = scanner.nextInt();
        System.out.print("评分: ");
        double score = scanner.nextDouble();
        scanner.nextLine();

        Movie movie = new Movie(movieId, name, director, actor, intro, duration, score);
        movieService.addMovie(movie);
        System.out.println("影片添加成功");
    }

    // 查询影片（经理功能）
    private static void queryMovies() {
        System.out.println("\n===== 查询影片 =====");
        System.out.print("影片名称(模糊查询，回车忽略): ");
        String name = scanner.nextLine();
        System.out.print("导演(模糊查询，回车忽略): ");
        String director = scanner.nextLine();
        System.out.print("主演(模糊查询，回车忽略): ");
        String actor = scanner.nextLine();

        List<Movie> result = movieService.queryMovies(
                name.isEmpty() ? null : name,
                director.isEmpty() ? null : director,
                actor.isEmpty() ? null : actor
        );

        System.out.println("\n查询结果:");
        for (Movie movie : result) {
            System.out.printf("ID: %s, 名称: %s, 导演: %s, 主演: %s, 评分: %.1f%n",
                    movie.getMovieId(), movie.getName(), movie.getDirector(),
                    movie.getActor(), movie.getScore());
        }
    }

    // 售票（前台功能）
    private static void sellTicket() {
        System.out.println("\n===== 售票 =====");
        listAllShows();

        System.out.print("请输入要购买的场次ID: ");
        String showId = scanner.nextLine();

        Show selectedShow = null;
        for (Show show : showService.getAllShows()) {
            if (show.getShowId().equals(showId)) {
                selectedShow = show;
                break;
            }
        }

        if (selectedShow == null) {
            System.out.println("无效的场次ID");
            return;
        }

        System.out.println("当前场次: " + selectedShow.getMovie().getName() +
                " 时间: " + selectedShow.getTime().toString().substring(0, 16) +
                " 厅: " + selectedShow.getHall().getHallName() +
                " 票价: " + selectedShow.getPrice());

        System.out.print("请输入购买票数: ");
        int ticketCount = scanner.nextInt();
        scanner.nextLine();

        List<Seat> seats = new ArrayList<>();
        for (int i = 0; i < ticketCount; i++) {
            System.out.printf("请输入第%d个座位的行号: ", i + 1);
            int row = scanner.nextInt();
            System.out.printf("请输入第%d个座位的列号: ", i + 1);
            int col = scanner.nextInt();
            scanner.nextLine();

            if (!selectedShow.getHall().checkSeatAvailable(row, col)) {
                System.out.println("该座位已售出或不存在，请重新选择");
                i--; // 重新输入当前座位
                continue;
            }

            seats.add(new Seat(row, col, false));
        }

        Ticket ticket = ticketService.sellTicket(selectedShow, seats);
        if (ticket != null) {
            System.out.println("售票成功！票号: " + ticket.getTicketId());
            System.out.println("座位: " + seats);
            System.out.println("总价: " + ticket.getPrice());
        } else {
            System.out.println("售票失败");
        }
    }

    // 退票（前台功能）
    private static void refundTicket() {
        System.out.println("\n===== 退票 =====");
        System.out.print("请输入票号: ");
        String ticketId = scanner.nextLine();

        if (ticketService.refundTicket(ticketId)) {
            System.out.println("退票成功");
        } else {
            System.out.println("退票失败（票号不存在或已过退票时间）");
        }
    }

    // 列出所有场次（通用功能）
    private static void listAllShows() {
        System.out.println("\n===== 所有场次 =====");
        for (Show show : showService.getAllShows()) {
            System.out.printf("场次ID: %s, 影片: %s, 时间: %s, 厅: %s, 票价: %.1f%n",
                    show.getShowId(), show.getMovie().getName(),
                    show.getTime().toString().substring(0, 16),
                    show.getHall().getHallName(), show.getPrice());
        }
    }

    // 修改密码（通用功能）
    private static void changePassword() {
        System.out.print("请输入旧密码: ");
        String oldPwd = scanner.nextLine();
        System.out.print("请输入新密码: ");
        String newPwd = scanner.nextLine();
        System.out.print("请确认新密码: ");
        String confirmPwd = scanner.nextLine();

        if (!newPwd.equals(confirmPwd)) {
            System.out.println("两次输入的密码不一致");
            return;
        }

        User currentUser = UserContext.getCurrentUser();
        if (currentUser.changePassword(oldPwd, newPwd)) {
            System.out.println("密码修改成功");
            new Log("修改密码", currentUser.getUsername()).saveLog();
        } else {
            System.out.println("旧密码错误，修改失败");
        }
    }

    // 保存所有数据到文件（程序退出时调用）
    private static void saveAllData() {
        userService.saveUsers();
        movieService.saveMovies();
        showService.saveShows();
        ticketService.saveTickets();
        System.out.println("数据已保存到文件");
    }
}
